package com.lkpstudy.rbac.mapper;

import com.lkpstudy.rbac.entity.Auth;
import com.lkpstudy.rbac.entity.Role;
import com.lkpstudy.rbac.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
//import io.lettuce.core.dynamic.annotation.Param;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
* @author likaiping
* @description 针对表【user(系统用户)】的数据库操作Mapper
* @createDate 2024-04-17 20:25:23
* @Entity com.lkpstudy.rbac.entity.User
*/
public interface UserMapper extends BaseMapper<User> {
    /**
     * 根据用户名查询用户id
     * @param username 用户名
     * @return 用户id
     */
    @Select("SELECT id FROM user WHERE username=#{username}")
    Long selectIdByUsername(@Param("username") String username);

    /**
     * 根据用户id查询用户角色列表
     * @param userId 用户id
     * @return 用户角色列表
     */
    @Select("SELECT id,rolename from user_role LEFT JOIN role ON user_role.role_id = role.id where user_id =#{userId}")
    List<Role> listRolesByUserId(@Param("userId") Long userId);

    /**
     * 根据用户id查询用户角色id列表
     * @param userId 用户id
     * @return 用户角色id列表
     */
    @Select("SELECT id from user_role LEFT JOIN role ON user_role.role_id = role.id where user_id =#{userId}")
    List<Long> listRolesIdsByUserId(@Param("userId") Long userId);

    /**
     * 根据角色id查询权限
     * @param roleIds 角色id
     * @return 权限列表
     */
    @Select("<script>" +
            "SELECT DISTINCT auth.* FROM role_auth LEFT JOIN auth ON role_auth.auth_id=auth.id WHERE role_auth.role_id IN " +
            "<foreach collection='roleIds' item='item' open='(' separator=',' close=')'>" +
            "   #{item}" +
            "</foreach>" +
            "</script>")
    List<Auth> listAuthsByRoleIds(@Param("roleIds") List<Long> roleIds);

    /**
     * 根据用户id删除其所有角色
     * @param userId 用户id
     * @return
     */
    @Delete("DELETE FROM user_role WHERE user_id=#{userId}")
    boolean deleteRolesByUserId(@Param("userId") Long userId);

    /**
     * 根据用户id给其添加角色
     * @param userId 用户id
     * @param roleIds 需要添加的角色id列表
     * @return
     */
    @Insert("<script>" +
            "INSERT INTO user_role(user_id,role_id) VALUES " +
            "<foreach collection='roleIds' item='item' separator=',' >" +
            "   (#{userId},#{item})" +
            "</foreach>" +
            "</script>")
    boolean insertRolesBatch(@Param("userId") Long userId,@Param("roleIds") List<Long> roleIds);
}




